package com.pachong.baidumaplib.location.city;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.android.frameworkbase.utils.io.SharePreferenceUtil;
import com.pachong.baidumaplib.R;
import com.pachong.baidumaplib.location.entity.CityEntity;
import com.pachong.baidumaplib.location.service.LocationService;
import com.pachong.baidumaplib.location.utils.GsonUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.List;

public class CityChoiceActivity extends BaseActivity implements View.OnClickListener {

    private ListView mLvAllCity;
    private static final String FILE_NAME = "city.txt";
    private static final String LOCATION_INFO = "location_info";
    private static final String CITY_NAME = "city_name";
    private LocationService locationService;
    private TextView mTvCurrentCity;
    private List<CityEntity.AllBean> mAllCityList;
    private String mCityCode;
    private String mCityName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_city_choice, null);
        initData();
        initView(view);
        return view;
    }

    /**
     * 显示定位结果
     */
    public void showResult(String result, BDLocation location) {
        try {
            if (mTvCurrentCity != null)
                if (location.getLocType() == BDLocation.TypeGpsLocation
                        || location.getLocType() == BDLocation.TypeNetWorkLocation
                        || location.getLocType() == BDLocation.TypeOffLineLocation) {
                    mTvCurrentCity.setText(result);
                    saveLocationInfo(getString(R.string.location_state_success));
                    /**
                     发送广播 传递当前定位城市名
                     */
                    Intent broadcastIntent = new Intent();
                    broadcastIntent.putExtra(CITY_NAME, result);
                    sendBroadcast(broadcastIntent);
                } else if (location.getLocType() == BDLocation.TypeServerError
                        || location.getLocType() == BDLocation.TypeNetWorkException
                        || location.getLocType() == BDLocation.TypeCriteriaException) {
                    mTvCurrentCity.setText(getString(R.string.city_choice_fail));
                    saveLocationInfo(getString(R.string.location_state_fail));
                }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        locationService = new LocationService(getBaseContext());
        locationService.registerListener(mListener);
        int type = getIntent().getIntExtra("from", 0);
        if (type == 0) {
            locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        } else if (type == 1) {
            locationService.setLocationOption(locationService.getOption());
        }
        new LocationRunnable().run();
    }

    private class LocationRunnable implements Runnable {

        @Override
        public void run() {
            locationService.start();// 定位SDK
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        locationService.unregisterListener(mListener); //注销掉监听
        locationService.stop(); //停止定位服务
        saveLocationInfo(getString(R.string.location_state_idle));
    }

    private void initData() {
        String jsonSrc = getJsonFile();
        CityEntity cityEntity = GsonUtils.parseJSON(jsonSrc, CityEntity.class);
        mAllCityList = cityEntity.getAll();
    }

    private String getJsonFile() {

        String result = "";
        try {
            InputStream is = getResources().getAssets().open(FILE_NAME);
            InputStreamReader inputStreamReader = new InputStreamReader(is);
            BufferedReader bf = new BufferedReader(inputStreamReader);
            String line = "";
            while ((line = bf.readLine()) != null)
                result += line;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    private void initView(View view) {
        mLvAllCity = (ListView) view.findViewById(R.id.lv_ctch_allcity);
        mTvCurrentCity = (TextView) view.findViewById(R.id.tv_ctch_currentcity);
        AllCityAdapter allCityAdapter = new AllCityAdapter();
        mLvAllCity.setAdapter(allCityAdapter);
        mLvAllCity.setOnItemClickListener(new AllCityListViewOnItemClickListener());
        saveLocationInfo(getString(R.string.location_state_working));
        mTvCurrentCity.setOnClickListener(new CurrentCityOnClickListener());
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.rlty_ctch_back) {
            finish();
        }
    }

    private class CurrentCityOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            saveLocationInfo(getString(R.string.location_state_success));
            locationService.start();
            Toast.makeText(getBaseContext(), "当前城市 : " + mTvCurrentCity.getText(), Toast.LENGTH_SHORT).show();
        }
    }

    private void saveLocationInfo(String locationState) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss ");
        String location_time = formatter.format(new java.util.Date());
        String location_data =
                "最近定位的时间: " + location_time + '\t'
                        + " 定位城市名称:" + mCityName + '\t'
                        + "定位城市的Code:" + mCityCode + '\t'
                        + "定位工作的状态:" + locationState;
        SharePreferenceUtil.saveString(CityChoiceActivity.this, LOCATION_INFO, LOCATION_INFO, location_data);
    }

    private class AllCityAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mAllCityList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = getLayoutInflater().inflate(R.layout.item_city_name, null);
            TextView tvCityName = (TextView) view.findViewById(R.id.tv_item_cityname);
            tvCityName.setText(mAllCityList.get(position).getCity().getName());
            return view;
        }
    }

    private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                StringBuffer sb = new StringBuffer(256);

                /**
                 * sb.append("time : ");
                 * 时间也可以使用systemClock.elapsedRealtime()方法 获取的是自从开机以来，每次回调的时间；
                 * location.getTime() 是指服务端出本次结果的时间，如果位置不发生变化，则时间不变
                 sb.append(location.getTime());
                 sb.append("\nerror code : ");
                 sb.append(location.getLocType());   //获得错误代码
                 sb.append("\nlatitude : ");
                 sb.append(location.getLatitude());  //获得纬度
                 sb.append("\nlontitude : ");
                 sb.append(location.getLongitude()); //获得精度
                 sb.append("\nradius : ");
                 sb.append(location.getRadius());    //获得半径
                 sb.append("\nCountryCode : ");
                 sb.append(location.getCountryCode());   //获得国家代码
                 sb.append("\nCountry : ");
                 sb.append(location.getCountry());   //获得国家名
                 sb.append("\ncitycode : ");
                 sb.append(location.getCityCode());  //获得城市代码
                 sb.append("\ncity : ");
                 sb.append(location.getCity());  //获得城市名
                 sb.append("\nDistrict : ");
                 sb.append(location.getDistrict());  //获得城市区名
                 sb.append("\nStreet : ");
                 sb.append(location.getStreet());    //获得街道名
                 sb.append("\naddr : ");
                 sb.append(location.getAddrStr());   //获得地址
                 sb.append("\nDescribe: ");
                 sb.append(location.getLocationDescribe());  //获得描述
                 sb.append("\nDirection(not all devices have value): ");
                 sb.append(location.getDirection());
                 sb.append("\nPoi: ");
                 if (location.getPoiList() != null && !location.getPoiList().isEmpty()) {
                 for (int i = 0; i < location.getPoiList().size(); i++) {
                 Poi poi = (Poi) location.getPoiList().get(i);
                 sb.append(poi.getName() + ";");
                 }
                 }
                 if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                 sb.append("\nspeed : ");
                 sb.append(location.getSpeed());// 单位：km/h
                 sb.append("\nsatellite : ");
                 sb.append(location.getSatelliteNumber());
                 sb.append("\nheight : ");
                 sb.append(location.getAltitude());// 单位：米
                 sb.append("\ndescribe : ");
                 sb.append("gps定位成功");
                 } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                 // 运营商信息
                 sb.append("\noperationers : ");
                 sb.append(location.getOperators());
                 sb.append("\ndescribe : ");
                 sb.append("网络定位成功");
                 } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                 sb.append("\ndescribe : ");
                 sb.append("离线定位成功，离线定位结果也是有效的");
                 } else if (location.getLocType() == BDLocation.TypeServerError) {
                 sb.append("\ndescribe : ");
                 sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
                 } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                 sb.append("\ndescribe : ");
                 sb.append("网络不同导致定位失败，请检查网络是否通畅");
                 } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                 sb.append("\ndescribe : ");
                 sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
                 }*/

                mCityName = location.getCity();
                mCityCode = location.getCityCode();
                showResult(mCityName, location);
            }
        }
    };

    private class AllCityListViewOnItemClickListener implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(CityChoiceActivity.this, mAllCityList.get(position).getCity().getName(), Toast.LENGTH_SHORT).show();
        }
    }
}
